package com.jiajia.study.mylist.circle;


/**
 * 环形队列：
 *      用数组来实现
 *
 * @author zjiajia
 * @date 2021/1/16 23:01
 */
public class CircleQueue<E> {
    /**
     * 头节点
     */
    private int front ;
    /**
     * 队列大小
     */
    private int size;
    /**
     * 队列
     */
    private E[] elements;
    /**
     * 默认容量的大小
     */
    private final int DEFAULT_CAPACITY = 10;

    public CircleQueue(){
        elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    /**
     * 队列的大小
     * @return  队列的大小
     */
    public int size(){
        return size;
    }

    /**
     * 是否为空
     * @return  是否为空
     */
    public boolean isEmpty(){
        return size == 0;
    }

    /**
     * 队头
     * @return  查看队头元素
     */
    public E front(){
        return elements[front];
    }

    /**
     * 出队
     * @return 队头元素
     */
    public E  deQueue(){
        E frontElement = elements[front];
        elements[front] = null;
        size -- ;
        front = ((front + 1) % elements.length);
        return frontElement;
    }

    /**
     * 入队
     * @param element   元素
     */
    public void enQueue(E element){
        ensureCapacity(size + 1);
        // 队尾的位置
        int tailIndex = (front + size ) % elements.length ;
        elements[tailIndex] = element;
        size ++ ;
    }


    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("capcacity=").append(elements.length)
                .append(" size=").append(size)
                .append(" front=").append(front)
                .append(", [");
        for (int i = 0; i < elements.length; i++) {
            if (i != 0) {
                string.append(", ");
            }

            string.append(elements[i]);
        }
        string.append("]");
        return string.toString();
    }

    private void ensureCapacity(int capacity){
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) {
            return;
        }


        // 新容量为旧容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[(i + front)%elements.length];
        }
        elements = newElements;

        // 重置front
        front = 0;

    }
}
